"""
配置管理模块
负责加载和管理系统配置
"""

import os
import yaml
from typing import Dict, Any, Optional
from pathlib import Path


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_path: Optional[str] = None):
        self.config_path = config_path or self._get_default_config_path()
        self.config = self._load_config()
        
    def _get_default_config_path(self) -> str:
        """获取默认配置文件路径"""
        current_dir = Path(__file__).parent.parent
        return str(current_dir / "config" / "default.yaml")
        
    def _load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                config = yaml.safe_load(f)
                
            # 环境变量替换
            config = self._substitute_env_vars(config)
            
            # 配置验证
            self._validate_config(config)
            
            return config
            
        except Exception as e:
            print(f"Failed to load config from {self.config_path}: {e}")
            return self._get_default_config()
            
    def _substitute_env_vars(self, config: Dict) -> Dict:
        """替换环境变量"""
        import re
        
        def replace_env_vars(obj):
            if isinstance(obj, dict):
                return {k: replace_env_vars(v) for k, v in obj.items()}
            elif isinstance(obj, list):
                return [replace_env_vars(item) for item in obj]
            elif isinstance(obj, str):
                # 替换 ${VAR_NAME} 格式的环境变量
                pattern = r'\$\{([^}]+)\}'
                matches = re.findall(pattern, obj)
                for match in matches:
                    env_value = os.getenv(match, '')
                    obj = obj.replace(f'${{{match}}}', env_value)
                return obj
            else:
                return obj
                
        return replace_env_vars(config)
        
    def _validate_config(self, config: Dict):
        """验证配置"""
        required_sections = ['server', 'storage', 'subscription']
        
        for section in required_sections:
            if section not in config:
                raise ValueError(f"Missing required config section: {section}")
                
    def _get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            'server': {
                'host': '0.0.0.0',
                'port': 7880,
                'debug': False
            },
            'storage': {
                'data_dir': 'data',
                'models_file': 'models.json',
                'subscriptions_file': 'subscriptions.json',
                'servers_file': 'servers.json',
                'clients_file': 'clients.json'
            },
            'subscription': {
                'enabled': True,
                'default_check_interval': 1800,
                'max_concurrent_checks': 5
            },
            'logging': {
                'level': 'INFO',
                'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            }
        }
        
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值，支持点号分隔的嵌套键"""
        keys = key.split('.')
        current = self.config
        
        for k in keys:
            if isinstance(current, dict) and k in current:
                current = current[k]
            else:
                return default
                
        return current
        
    def get_server_config(self) -> Dict[str, Any]:
        """获取服务器配置"""
        return self.config.get('server', {})
        
    def get_storage_config(self) -> Dict[str, Any]:
        """获取存储配置"""
        return self.config.get('storage', {})
        
    def get_subscription_config(self) -> Dict[str, Any]:
        """获取订阅配置"""
        return self.config.get('subscription', {})
        
    def get_logging_config(self) -> Dict[str, Any]:
        """获取日志配置"""
        return self.config.get('logging', {})


# 全局配置实例
config = ConfigManager()
